Bubble e Selection Sort

prof. Matteo Lugli

Created: 2024-04-12 ven 23:50

Table of Contents

Bubble Sort


Codice

def bubble(l):
        i = 0
        n = len(l)
        flipped = False
        while(True):
                while i < n-1:
                        if l[i] > l[i+1]:
                                temp = l[i]
                                l[i] = l[i+1]
                                l[i+1] = temp
                                flipped = True
                        i+=1
                i = 0
                if not flipped:
                        print("Sorting done")
                        break
                flipped = False
if __name__ == "__main__":
        l = [3,1,2,3,1,5,1,3,2,5,6,3,2,1]
        bubble_sort(l)
        print(l)

Selection Sort


Codice

#todo: swap function, index
def argmin(l, i):
        min_element = min(l[i:])
        for j in range(i, len(l)):
                if l[j] == min_element:
                        return j
        return -1

def selection_sort(l,i):
        if i == len(l)-1:
                return

        # find POSITION of min element
        min_pos = argmin(l,i) #1

        #swap l[min_pos] and l[i]
        temp = l[min_pos]
        l[min_pos] = l[i]
        l[i] = temp

        #recursive call
        selection_sort(l,i+1)

l = [3,1,2,3,1,5,1,3,2,5,6,3,2,1]
selection_sort(l, 0)
print(l)